package controller;

import entity.User;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.cell.PropertyValueFactory;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.ResourceBundle;
import java.util.Timer;
import java.util.TimerTask;

public class ChatRoomController implements Initializable {

    @FXML
    private Button subBtm;

    @FXML
    private TextArea meID;

    @FXML
    private TextArea whoId;

    @FXML
    private Button clearBtn;//清除输入的内容

    @FXML
    private Button exitBtn;//退出

    @FXML
    private Button nickBtn;//修改昵称

    @FXML
    private TableColumn<User, String> ipClonum;

    @FXML
    private TextArea nickInput;//输入框

    @FXML
    private TableColumn<User, String> protColnum;

    @FXML
    private TableColumn<User, String> userColnum;

    @FXML
    private TableView<User> tabId;

    private Socket socket;
    private InputStream is;
    private OutputStream os;
    private Timer timer;
    private SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private String selfIpPort;

    @FXML
    void clear_btn(ActionEvent event) {
        System.out.println("xxxx");
    }

    @FXML
    void sub_btn(ActionEvent event) {
        // 获取多选的用户列表
        java.util.List<User> selectedUsers = tabId.getSelectionModel().getSelectedItems();
        String message = whoId.getText();
        if (!message.isEmpty() && !selectedUsers.isEmpty()) {
            try {
                String currentTime = df.format(new Date());
                for (User selectedUser : selectedUsers) {
                    String targetUser = selectedUser.getIp() + ":" + selectedUser.getPort();
                    String fullMessage = targetUser + "|" + currentTime + "：" + message;
                    os.write(fullMessage.getBytes());

                    // 将发送的信息显示在 meId 控件上
                    Platform.runLater(() -> {
                        meID.appendText("\n你在 " + currentTime + " 向 " + selectedUser.getNick() + " 发送了消息：\n" + message);
                    });
                }
                whoId.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @FXML
    void exit(ActionEvent event) {
        try {
            if (socket != null &&!socket.isClosed()) {
                socket.close();
            }
            if (timer != null) {
                timer.cancel();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }

    @FXML
    void changeNick(ActionEvent event) {
        String newNick = nickInput.getText().trim();
        if (!newNick.isEmpty()) {
            try {
                String command = "NICK|" + newNick;
                os.write(command.getBytes());
                nickInput.clear();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void initialize(java.net.URL location, ResourceBundle resources) {
        ipClonum.setCellValueFactory(new PropertyValueFactory<>("ip"));
        protColnum.setCellValueFactory(new PropertyValueFactory<>("port"));
        userColnum.setCellValueFactory(new PropertyValueFactory<>("nick"));

        // 设置 TableView 支持多选
        tabId.getSelectionModel().setSelectionMode(javafx.scene.control.SelectionMode.MULTIPLE);

        try {
            InetAddress inetAddress = InetAddress.getByName("MyBook");
            socket = new Socket(inetAddress, 8888);
            is = socket.getInputStream();
            os = socket.getOutputStream();
            byte[] bytes = new byte[1024];
            int bytesRead = is.read(bytes);
            if (bytesRead != -1) {
                String welcomeMessage = new String(bytes, 0, bytesRead);
                meID.setText(welcomeMessage);
            }

            // 获取自身的 IP 和端口
            selfIpPort = socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort();

            // 定时任务，每秒更新一次在线用户列表或接收消息
            timer = new Timer();
            timer.scheduleAtFixedRate(new TimerTask() {
                @Override
                public void run() {
                    try {
                        byte[] buffer = new byte[1024];
                        int read = is.read(buffer);
                        if (read != -1) {
                            String data = new String(buffer, 0, read);
                            if (data.contains(",")) {
                                updateUserList(data);
                            } else if (data.startsWith("NICK_UPDATE|")) {
                                updateNick(data.substring(12));
                            } else {
                                receiveMessage(data);
                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, 0, 1000);
        } catch (UnknownHostException e) {
            System.err.println("无法解析主机名: " + e.getMessage());
        } catch (IOException e) {
            System.err.println("网络通信错误: " + e.getMessage());
        }
    }

    private void updateUserList(String userInfo) {
        Platform.runLater(() -> {
            tabId.getItems().clear();
            String[] users = userInfo.split(",");
            for (String user : users) {
                if (!user.equals(selfIpPort)) {
                    String[] parts = user.split(":");
                    if (parts.length == 2) {
                        String ip = parts[0];
                        String port = parts[1];
                        User newUser = new User(ip, port, "");
                        tabId.getItems().add(newUser);
                    }
                }
            }
        });
    }

    private void updateNick(String nickInfo) {
        Platform.runLater(() -> {
            String[] parts = nickInfo.split(":", 2);
            if (parts.length == 2) {
                String userKey = parts[0];
                String newNick = parts[1];
                for (User user : tabId.getItems()) {
                    if ((user.getIp() + ":" + user.getPort()).equals(userKey)) {
                        user.setNick(newNick);
                        break;
                    }
                }
            }
        });
    }

    private void receiveMessage(String message) {
        Platform.runLater(() -> {
            meID.appendText("\n收到消息了时间为 " + message);
        });
    }
}